package com.wxs.controller;

import com.alibaba.fastjson.JSONObject;
import com.wxs.pojo.Article;
import com.wxs.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @GetMapping("/toEditor")
    public String toEditor(){
        return "editor";
    }

    @PostMapping("/addArticle")
    public String addArticle(Article article){
        System.out.println("提交文章: "+ article.toString());
        articleService.addArticle(article);
        return "editor";
    }

    @RequestMapping("/file/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file",required = true)MultipartFile file, HttpServletRequest request) throws IOException {

        if(file.isEmpty()){
            System.out.println("file is empty");
        }

        String path = System.getProperty("user.dir")+"/upload/";

        /*按照月份进行分类*/
        Calendar instance = Calendar.getInstance();
        String month = (instance.get(Calendar.MONTH)+1)+"月";
        path = path + month;

        File realpath = new File(path);
        if(!realpath.exists()){
            boolean res = realpath.mkdirs();
            System.out.println("create file " + res);
        }

        /*upload file 地址设计*/
        System.out.println("upload file to "+ realpath);

        /*解决文件名字问题*/
        String originFileName = file.getOriginalFilename();
        String suffixName = originFileName.substring(originFileName.lastIndexOf("."));
        String fileName = "blog-" + UUID.randomUUID().toString().replaceAll("-","") + suffixName;
        System.out.println("success upload "+ fileName);
        file.transferTo(new File(realpath+"/"+fileName));

        /*给editor 反馈*/
        JSONObject res = new JSONObject();
        res.put("url","/upload/"+month+"/"+ fileName);
        res.put("success",1);
        res.put("message","upload success");

        return res;
    }


    @GetMapping("/{id}")
    public String show(@PathVariable("id") Integer id, Model model){
        Article article = articleService.getArticleById(id);
        model.addAttribute("article",article);
        return "article";
    }

}
